//
//  BSTopicCell.m
//  Baisijie
//
//  Created by 王建伟 on 2017/3/22.
//  Copyright © 2017年 RangGuangyu. All rights reserved.
//

#import "BSTopicCell.h"
#import "BSTopicItem.h"
#import "UIImageView+Extension.h"
#import "BSPictureView.h"
#import "BSVideoView.h"
#import "BSVoiceView.h"

@interface BSTopicCell ()

@property (weak, nonatomic) IBOutlet UIImageView *headerIcon;
@property (weak, nonatomic) IBOutlet UILabel *userNameLbl;
@property (weak, nonatomic) IBOutlet UIImageView *vipIcon;
@property (weak, nonatomic) IBOutlet UILabel *passTimeLbl;
@property (weak, nonatomic) IBOutlet UILabel *contentTextLbl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentTextLblH;
@property (weak, nonatomic) IBOutlet UIButton *upDownBtn;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *dingBtn;
@property (weak, nonatomic) IBOutlet UIButton *caiBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
@property (weak, nonatomic) IBOutlet UIButton *commentBtn;
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerViewH;
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentViewH;
/** 中间的图片视图 */
@property (nonatomic ,weak) BSPictureView *pictureView;
/** 中间的视频视图 */
@property (nonatomic ,weak) BSVideoView *videoView;
/** 中间的音频视图 */
@property (nonatomic ,weak) BSVoiceView *voiceView;

@end

@implementation BSTopicCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.autoresizingMask = UIViewAutoresizingNone;
}
- (BSPictureView *)pictureView {
    if (!_pictureView) {
        BSPictureView *pictureView = [BSPictureView bs_viewFromNib];
        pictureView.frame = CGRectMake(0, BSMargin, KScreenW - 2 * BSMargin, 0);
        [_centerView addSubview:pictureView];
        _pictureView = pictureView;
    }
    return _pictureView;
}
- (BSVideoView *)videoView {
    if (!_videoView) {
        BSVideoView *videoView = [BSVideoView bs_viewFromNib];
        videoView.frame = CGRectMake(0, BSMargin, KScreenW - 2 * BSMargin, 0);
        [_centerView addSubview:videoView];
        _videoView = videoView;
    }
    return _videoView;
}
- (BSVoiceView *)voiceView {
    if (!_voiceView) {
        BSVoiceView *voiceView = [BSVoiceView bs_viewFromNib];
        voiceView.frame = CGRectMake(0, BSMargin, KScreenW - 2 * BSMargin, 0);
        [_centerView addSubview:voiceView];
        _voiceView = voiceView;
    }
    return _voiceView;
}
- (void)setTopicItem:(BSTopicItem *)topicItem {
    _topicItem = topicItem;
    [self.headerIcon bs_circleImageWithUrl:topicItem.u.header.firstObject placeholderImage:@"defaultUserIcon"];
    self.userNameLbl.text = topicItem.u.name;
    self.vipIcon.hidden = !topicItem.u.is_vip;
    self.upDownBtn.selected = topicItem.showTextType == 1;
    if (topicItem.u.is_vip) {
        self.userNameLbl.textColor = [UIColor redColor];
    } else {
        self.userNameLbl.textColor = BSRGBColor(75, 160, 255, 1);
    }
    self.passTimeLbl.text = topicItem.passtime;
    self.contentTextLbl.text = topicItem.text;
    //设置底部按钮的文字
    [self setupBtn:self.dingBtn count:topicItem.up placeholder:@"顶"];
    [self setupBtn:self.caiBtn count:topicItem.down placeholder:@"踩"];
    [self setupBtn:self.shareBtn count:topicItem.forward placeholder:@"分享"];
    [self setupBtn:self.commentBtn count:topicItem.comment placeholder:@"评论"];
    [self setupCenterViewHeight];
    [self setupCommentView];
}
#pragma mark - 设置评论视图
- (void)setupCommentView {
    NSInteger count = _topicItem.top_comments.count;
    _commentView.hidden = !count;
    [_commentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat commentY = 0;
    CGFloat commentW = KScreenW - 4 * BSMargin;
    for (int i = 0; i < count; i ++) {
        BSCommentItem *item = _topicItem.top_comments[i];
        //创建用户评论Label
        UILabel *commentLbl = [[UILabel alloc] init];
        commentLbl.userInteractionEnabled = YES;
        commentLbl.font = [UIFont systemFontOfSize:15];
        commentLbl.numberOfLines = 0;
        [_commentView addSubview:commentLbl];
        //设置Label的富文本属性
        NSString *commentStr = [NSString stringWithFormat:@"%@：%@",item.u.name,item.content];
        NSRange nameR = [commentStr rangeOfString:item.u.name];
        nameR.length += 1;
        NSRange nameC = [commentStr rangeOfString:item.content];
        NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithString:commentStr];
        [attrs addAttribute:NSForegroundColorAttributeName value:BSRGBColor(75, 160, 255, 1) range:nameR];
        [attrs addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:nameC];
        commentLbl.attributedText = attrs;
        //设置label的位置
        CGSize size = [commentStr boundingRectWithSize:CGSizeMake(commentW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : commentLbl.font} context:nil].size;
        commentLbl.bs_x = BSMargin;
        commentLbl.bs_width = commentW;
        commentLbl.bs_height = size.height + 0.5 * BSMargin;
        commentLbl.bs_y = commentY + 0.5 * BSMargin;
        
        //在label的用户名上添加一个同等大小的按钮处理点击事件
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i + 10;
        btn.titleLabel.font = commentLbl.font;
        [btn setTitle:item.u.name forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        [btn sizeToFit];
        btn.bs_height = [item.u.name sizeWithAttributes:@{NSFontAttributeName : commentLbl.font}].height + 5;
        [btn addTarget:self action:@selector(usernameBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [commentLbl addSubview:btn];
        
        if ([item.cmt_type isEqualToString:@"audio"]) {
            UIButton *audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [audioBtn setBackgroundImage:[UIImage imageNamed:@"play-voice-bg"] forState:UIControlStateNormal];
            [audioBtn setBackgroundImage:[UIImage imageNamed:@"play-voice-bg-select"] forState:UIControlStateHighlighted];
            [audioBtn setImage:[UIImage imageNamed:@"play-voice-icon-2"] forState:UIControlStateNormal];
            [audioBtn setImage:
             [UIImage animatedImageWithImages:@[[UIImage imageNamed:@"play-voice-icon-0"],
                                                [UIImage imageNamed:@"play-voice-icon-1"],
                                                [UIImage imageNamed:@"play-voice-icon-2"]]
                                     duration:1]
                      forState:UIControlStateSelected];
            audioBtn.frame = CGRectMake(size.width + BSMargin, 0, 80, 30);
            commentLbl.bs_height = audioBtn.bs_height + 5;
            audioBtn.bs_centerY = commentLbl.bs_centerY;
            btn.bs_centerY = commentLbl.bs_height * 0.5;
            audioBtn.tag = i + 100;
            [audioBtn addTarget:self action:@selector(playAudio:) forControlEvents:UIControlEventTouchUpInside];
            [_commentView addSubview:audioBtn];
        }
        commentY += commentLbl.bs_height;
        //计算评论视图的高度
        if (i == count - 1) {
            _commentViewH.constant = CGRectGetMaxY(commentLbl.frame) + 0.5 * BSMargin;
        }
    }
}
#pragma mark - 评论中用户名按钮的点击
- (void)usernameBtnClick:(UIButton *)btn {
    NSInteger index = btn.tag - 10;
    BSCommentItem *item = _topicItem.top_comments[index];
    BSLog(@"%@",item.u.name)
}
- (void)playAudio:(UIButton *)btn {
    btn.selected = !btn.isSelected;
    NSInteger index = btn.tag - 100;
    BSCommentItem *item = _topicItem.top_comments[index];
    BSLog(@"%@",item.voiceuri)
    if (btn.isSelected) {   //播放音频
        
    } else {    //关闭音频
        
    }
}
#pragma mark - 计算中间图片视图的高度
- (void)setupCenterViewHeight {
    self.pictureView.hidden = YES;
    self.videoView.hidden = YES;
    self.voiceView.hidden = YES;
    _upDownBtn.hidden = YES;
    CGFloat cellW = KScreenW - 2 * BSMargin;
    NSDictionary *atts = @{NSFontAttributeName : _contentTextLbl.font};
    CGFloat textHeight = [_topicItem.text boundingRectWithSize:CGSizeMake(cellW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:atts context:nil].size.height;
    CGFloat textOneLineHeight = [@"百思不得姐" sizeWithAttributes:atts].height;
    _contentTextLblH.constant = textHeight + 1;
    
    if ([_topicItem.type isEqualToString:@"text"]) {
        if (_topicItem.showTextType == 0) {
            //未处理全文显示
            _upDownBtn.hidden = YES;
            _centerViewH.constant = 0;
        } else if (_topicItem.showTextType == 1) {
            //文字高度较大全文显示
            _upDownBtn.hidden = NO;
            _centerViewH.constant = 25;
        } else {
            //文字高度较大折叠显示
            _upDownBtn.hidden = NO;
            _centerViewH.constant = 25;
            _contentTextLblH.constant = textOneLineHeight * 7 + 1;
        }
    } else if ([_topicItem.type isEqualToString:@"image"]) {
        self.pictureView.hidden = NO;
        CGFloat imageH = cellW * _topicItem.image.height / _topicItem.image.width;
        if (imageH > KScreenW) {
            imageH = KScreenW;
        }
        _centerViewH.constant = imageH + 10;
        self.pictureView.bs_height = imageH;
        self.pictureView.gif = nil;
        self.pictureView.image = _topicItem.image;
    } else if ([_topicItem.type isEqualToString:@"gif"]) {
        self.pictureView.hidden = NO;
        CGFloat gifH = cellW * _topicItem.gif.height / _topicItem.gif.width;
        _centerViewH.constant = gifH + 10;
        self.pictureView.bs_height = gifH;
        self.pictureView.image = nil;
        self.pictureView.gif = _topicItem.gif;
    } else if ([_topicItem.type isEqualToString:@"video"]) {
        self.videoView.hidden = NO;
        CGFloat videoH = cellW * _topicItem.video.height / _topicItem.video.width;
        if (videoH > cellW) {
            videoH = cellW;
        }
        self.videoView.bs_height = videoH;
        self.videoView.bs_centerX = cellW * 0.5;
        _centerViewH.constant = videoH + 10;
        self.videoView.video = _topicItem.video;
    } else if ([_topicItem.type isEqualToString:@"audio"]) {
        self.voiceView.hidden = NO;
        _centerViewH.constant = 0;
    }
}
#pragma mark - 设置底部按钮的文字
- (void)setupBtn:(UIButton *)btn count:(NSInteger)count placeholder:(NSString *)placeholder {
    if (count >= 10000) {
        placeholder = [NSString stringWithFormat:@"%.1f万",count / 10000.0];
    } else if (count > 0) {
        placeholder = [NSString stringWithFormat:@"%zd",count];
    }
    [btn setTitle:placeholder forState:UIControlStateNormal];
}
#pragma mark - 查看全文或收起按钮的点击
- (IBAction)upDownBtnClick {
    _upDownBtn.selected = !_upDownBtn.isSelected;
    if (self.fullTextBtnClickBlock) {
        self.fullTextBtnClickBlock(_topicItem);
    }
}

- (void)setFrame:(CGRect)frame {
    frame.size.height -= 0.5;
    [super setFrame:frame];
}


@end
